import {ipcMain} from "electron";
import {deleteFolderRecursive, DirTree, mkDir, recursiveDirectory, saveFile} from "@/utils/main/file.uitls";
import {EXCLUDE_DIR, IMAGE_CONTAINER, NOTES_DIR} from "@/electron/const";
import {getGitAddress, gitPull} from "@/utils/main/git.utils";
import {MAIN_STORE} from "@/electron/main";
import fs from "fs";
import {syncNote} from "@/electron/git";
import {v4 as uuidv4} from 'uuid';
import {getSelectedNote} from "@/electron/application";

const path = require("path");

// 获取笔记本目录
ipcMain.handle("getNotes", async (): Promise<DirTree[]> => {
    const tree = recursiveDirectory(path.resolve(NOTES_DIR), [], EXCLUDE_DIR, false, true);
    for (let i = 0; i < tree.length; ++i) {
        tree[i].gitAddress = await getGitAddress(tree[i].path);
    }
    MAIN_STORE.notes = tree;
    return tree;
})

// 获取笔记下的目录树
ipcMain.handle("getNoteDirectories", async (e, name: string): Promise<DirTree[]> => {
    return recursiveDirectory(path.join(NOTES_DIR, name), [], EXCLUDE_DIR, true, true);
})

// 获取笔记目录的单层目录
ipcMain.handle("getCurrentItems", async (e, dir: string): Promise<DirTree[]> => {
    return recursiveDirectory(path.resolve(dir), [], EXCLUDE_DIR, false);
})

// 添加文件或文件夹
ipcMain.handle("addItem", (e, item: DirTree, data: any = "") => {
    try {
        let res: boolean;
        const p = path.resolve(item.path);
        if (item.isFile) {
            res = saveFile(p, data);
        } else {
            res = mkDir(p);
        }
        return res;
    } finally {
        syncNote();
    }
})

// 保存文件
ipcMain.handle("saveItem", (e, item: DirTree, data: any = "") => {
    try {
        saveFile(path.join(item.parentPath, item.name), data);
        if (item.name !== item.rename) {
            fs.renameSync(
                path.join(item.parentPath, item.name),
                path.join(item.parentPath, item.rename),
            )
        }
        return true;
    } catch (e) {
        return false;
    } finally {
        syncNote();
    }
})

// 读取文件
ipcMain.handle("readFile", (e, item: DirTree) => {
    try {
        return fs.readFileSync(path.join(item.parentPath, item.name), "utf-8");
    } catch (e) {
        return false;
    }
})

// 读取图片
ipcMain.on("readImage", (e, imageName: string) => {
    try {
        e.returnValue = fs.readFileSync(
            path.join(getSelectedNote().path, IMAGE_CONTAINER, imageName),
            "utf-8"
        );
    } catch (e) {
        e.returnValue = false;
    }
})

// 保存图片
ipcMain.on("saveImage", (e, base64: string) => {
    try {
        const imageName = uuidv4();
        const p = path.join(getSelectedNote().path, IMAGE_CONTAINER, imageName);
        saveFile(p, base64);
        e.returnValue = imageName
    } catch (e) {
        e.returnValue = false;
    }
})


// 重命名文件或文件名
ipcMain.handle("renameItem", (e, item: DirTree) => {
    try {
        const source = path.join(item.parentPath, item.name);
        const target = path.join(item.parentPath, item.rename);
        if (source === target) return true;
        if (!fs.existsSync(source)) return true;
        fs.renameSync(source, target);
        return true;
    } catch (e) {
        console.log(e);
        return false;
    } finally {
        syncNote();
    }
})

// 删除笔记
ipcMain.handle("deleteNote", async (e, name: string): Promise<boolean> => {
    const p = path.join(NOTES_DIR, name);
    if (!fs.existsSync(p)) {
        return true;
    }
    try {
        deleteFolderRecursive(p);
        syncNote();
        return true;
    } catch (e) {
        console.log(e);
        return false;
    }
})

// 删除项目
ipcMain.handle("deleteItem", async (e, item: DirTree): Promise<boolean> => {
    const p = path.join(item.parentPath, item.name);
    if (!fs.existsSync(p)) {
        return true;
    }
    try {
        if (item.isFile) {
            fs.unlinkSync(p);
            return true;
        }
        deleteFolderRecursive(p);
        return true;
    } catch (e) {
        console.log(e);
        return false;
    } finally {
        syncNote();
    }
})

// 移动项目
ipcMain.handle("moveItem", async (e, source: DirTree, target: DirTree) => {
    try {
        const s = path.join(source.parentPath, source.name);
        const t = path.join(target.path, source.name);
        if (s === t) return false;
        fs.renameSync(s, t);
        syncNote();
        return true;
    } catch (e) {
        console.log(e);
        return false;
    }
})

// 同步当前笔记
ipcMain.handle("pullNote", async (e) => {
    try {
        const note = getSelectedNote();
        if (!note) return false;
        return await gitPull(note.path);
    } finally {

    }
});
